#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author       : Abmer
# @Date         : 2019-08-06 10:09:39
# @Link         : https://gitee.com/edrik
# @Modified by  : Amber
# @Modified at  : 2019-08-31 10:01:32
# @Version      : v.0.1

import os
import logging

from .context import GlobalKV as gl
from .config import Config
from .capi.mbapi import api
from .error import *
from .nativejs import *
from .host import Host
from .platforms import BaseWindow

log = logging.getLogger(__name__)


class Window(BaseWindow, Host):
    """Wke window"""

    def __init__(self, title='', html='', is_debug=False, pos=(0, 0), size=(1280, 720), **kwargs):
        super(Window, self).__init__()

        self._title = title
        self._htmlpath = html
        self.pos = pos
        self.size = size
        self.is_debug = is_debug

        self.__dict__.update(kwargs)
        log.debug('Window.dict:  %r', self.__dict__)

        self.fn_as_javascript()

        self.webview = self._create_webview(pos, size)
        if not self.webview:
            raise WkeError('Could not create webview')

        if is_debug:
            self.debug()

        gl.app = self

    def fn_as_javascript(self):
        # bind  py-code to windows.call_py
        # run_js('console.log(11)')
        # run_js_by_frame('console.log(11)')

        log.debug('-' * 72)
        log.debug(':: bind_fn_as_javascript')
        for name, fn in gl.script.items():
            self.bind_fn_as_javascript(name, fn)

    def debug(self, params={}):
        print('-' * 72)
        debug_page = Config.DEBUG_PAGE
        inspector_file = os.path.abspath(os.path.join('.', debug_page))
        # log.debug('[Debug] config %r', inspector_file)
        inspector_file = 'file:///' + inspector_file.replace('\\', '/')
        print('[Debug] config %r' % inspector_file)
        dic = {
            'showDevTools': inspector_file,
            'wakeMinInterval': 10,
            'drawMinInterval': 3,
            'antiAlias': 1,
            # 'minimumFontSize': 12,
            # 'minimumLogicalFontSize': 12,
            # 'defaultFontSize': None,
            # 'defaultFixedFontSize': None
        }
        dic.update(params)

        print('api version: %r' % api.wkeVersion())
        versionStr = api.wkeVersionString()
        print(str(versionStr, encoding='utf8'))
        print('-' * 72)
        print('[Debug] Info:')
        for k, v in dic.items():
            print('%r %r' % (k, v))
            api.wkeSetDebugConfig(self.webview, k.encode(), str(v).encode())
        print('=' * 72)

    def mainloop(self):
        # add more
        res = super().mainloop()
        return res

    @property
    def title(self):
        return self._title

    @title.setter
    def title(self, title):
        self._title = title

    def load_url(self, url):
        log.debug(url)
        api.wkeLoadURLW(self.webview, url)

    def load_file(self, html=None):
        if not html:
            html = self._htmlpath
        html = self._htmlpath = os.path.abspath(html)
        '''
        if '://' not in html:
            url = 'file://' + os.path.abspath(html).replace('\\', '/')
        '''
        log.debug('Html File: %r', html)
        api.wkeLoadFileW(self.webview, html)

    def load_html(self, html="<html><body></body></html>", baseurl=None):
        log.debug('Html: ', html)
        if baseurl:
            api.wkeLoadHtmlWithBaseUrl(self.webview, html, baseurl)
        else:
            api.wkeLoadHTML(html)


if __name__ == '__main__':
    html = '../demo/pages/main.html'
    frame = Window("pyWke - demo", html, is_debug=True, size=(1024, 768))
    # frame.set_title('miniblink-demo')
    frame.load_file()
    frame.mainloop()
